from wtforms.validators import DataRequired, email, length, EqualTo, InputRequired
from wtforms.fields import StringField, PasswordField, SubmitField, TextAreaField, IntegerField
import wtforms
from exts import db
from models import EmailCaptchaModel, UserModel


class LoginForm(wtforms.Form):
    email = StringField(validators=[email(), DataRequired()])
    password = PasswordField(validators=[DataRequired()])


class RegisterForm(wtforms.Form):
    email = StringField(validators=[email(), DataRequired()])
    captcha = StringField(validators=[length(4, 4), DataRequired()])
    username = StringField(validators=[length(3, 30), DataRequired()])
    password = PasswordField(validators=[length(min=4, max=20), DataRequired()])
    password_confirm = PasswordField(validators=[DataRequired(), EqualTo('password')])

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        # 验证码不区分大小写
        if not captcha_model or captcha_model.captcha.lower() != captcha.lower():
            print('Captcha error!')
            raise wtforms.ValidationError('邮箱验证码错误!')
    
    def validate_email(self, field):
        email = field.data
        user_model = UserModel.query.filter_by(email=email).first()
        if user_model:
            print('Email validate error!')
            raise wtforms.ValidationError('邮箱已存在!')

 
class QuestionForm(wtforms.Form):
    title = StringField(validators=[DataRequired(), length(3, 200)])
    content = TextAreaField(validators=[DataRequired()])


class AnswerForm(wtforms.Form):
    content = StringField(validators=[DataRequired(), length(1)])
    # question_id = IntegerField(validators=[InputRequired()])